<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/18
 * Time: 16:42
 */

namespace app\index\controller;
use app\index\service;
use think\App;
use think\Controller;
use think\Request;
use think\facade\Session;


class Common extends Controller{
    private $_callback;

    public function __construct(App $app = null,Request $request){

         $me=$request->method();
        if($me!=='POST'){
             echo $this->jiami(['code'=>'1002','msg'=>'请使用POST传参','data'=>json([])]);
             die;
          }
          //登录接口不限制访问
           if($request->controller()!=='Login'){
//        if(Session::get('u_id')==null || Session::get('shop_id')==null){
//            echo $this->jiami(['code'=>'1002','msg'=>'请登录']);
//            die;
//        }
           }
        //参数解密
        $this->param= $request->post();
       $this->param=$this->jiemi($request->post('data'));
        parent::__construct($app);
    }

    public function jiami($data)
    {
        $jm = new service\Aes2();
        $data = json_encode($data);
        $data = $jm->encrypt($data);
        $arr=['data'=>$data];
        return json($arr);
    }

    public function jiemi($data)
    {
        $jm = new service\Aes2();
        $data = $jm->decrypt($data);
        $data = json_decode($data, true);
        return $data;
    }

    public function __destruct()
    {
        if (!empty($this->_callback)) {
            $this->return['callback'] = $this->_callback;
        }
        if (empty($this->return)) {
            return true;
        }

        echo json_encode($this->return);
        return true;
    }
    private function get_token($userid){
       $token=$userid.'_'.MD5($userid.uniqid().rand(00000000,99999999)); //随机数
       $file_dir=APP_PATH.'token/'.$userid.'/';
       if(!@is_dir($file_dir)){
          @mkdir($file_dir,0777,true);
       }else{  //删除之前所有的token文件
          $dir_token=scandir($file_dir);
          foreach($dir_token as $key => $value){
             if($value == '.' || $value == '..'){}else{
                unlink($file_dir.$value);
             }
          }
       }
       $fh = fopen($file_dir.$token,'w');
       fwrite($fh,serialize(array('time'=>time(),'token'=>$token,'userid'=>$userid))); //这个根据自己的需求去对应的添加数据
       fclose($fh);
       return $token;
    }
}